package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.uitls.MD5Util;
import com.example.forum.uitls.StringUtil;
import com.example.forum.uitls.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
//日志注解
@Slf4j
//第一级映射
@RequestMapping("/user")
//返回json格式的控制器
@RestController
public class UserController {
    //注入Service层用户接口
    @Resource
    IUserService userService;

    @ApiOperation("用户注册")
    @RequestMapping("/register")
    //用户注册
    public AppResult<User> register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                                    @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                                    @ApiParam("密码") @RequestParam("password") @NonNull String password,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") String passwordRepeat){
        //校验密码与确认密码是否相同
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //1.生成盐
        String salt = UUIDUtil.UUID_32();
        //2.生成密码的密文
        String encryptPassword = MD5Util.md5Salt(password,salt);
        //3.设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        //调用Service层
        userService.creatNormalUser(user);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @RequestMapping("/login")
    public AppResult login (HttpServletRequest request,
                            @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                            @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //1.调用service中login方法，返回用户数据
        User user = userService.login(username,password);
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回错误
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //如果登录成功把user设置到session中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回success
        return AppResult.success(user);
    }

    /**
     * 获取登陆用户信息
     * @param request
     * @return用户信息
     */
    @ApiOperation("获取登录用户信息 ")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        User user = null;
        if (id == null) {
            //获取session对象
            HttpSession session = request.getSession(false);
            //获取用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            user = userService.selectById(id);
        }
        //返回用户信息
        return AppResult.success(user);
    }

    @ApiOperation("退出")
    @PostMapping("/logout")
    public AppResult logOut(HttpServletRequest request) {
        //获取session
        HttpSession session = request.getSession(false);
        // 判断session
        if (session != null) {
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改用户信息
     * @param id 用户id
     * @param gender 性别
     * @param nickname 昵称
     * @param phoneNum 电话号码
     * @param email 邮箱地址
     * @param remark 个人简介
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/modify")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("用户Id") @RequestParam("id") @NonNull Long id,
                                 @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                 @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                 @ApiParam("电话号码") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                 @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                 @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        // 校验
        if (gender == null
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(remark)) {
            // 参数同时为空时返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        // 校验传入的Id是否为当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getId() != id) {
            // 返回错误
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED.toString());
        }
        // 调用service
        userService.modify(id, gender, nickname, phoneNum, email, remark);
        // 重新获取用户信息，更新session
        user = userService.selectById(id);
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 返回结果
        return AppResult.success();
    }
}
